package com.lsabcd.dubbo.test;

import java.util.ArrayList;
import java.util.List;

public class Limiter {
    // ms
    private int interval;
    // ms
    private int windowSize;

    private List<Window> windows;

    public Limiter(int interval, int windowSize) {
        this.interval = interval;
        this.windowSize = windowSize;
        int windowCount = interval / windowSize;
        windows = new ArrayList<Window>(windowCount);
        for (int i = 0; i < windowCount; i++) {
            windows.add(new Window(interval,1L));
        }
    }

    public boolean submit(WindowItem item){

        long now = System.currentTimeMillis();
        int t = (int) (now % interval);

        // 计算写入第几个窗口
        int index = t / windowSize + (t!=0 && t % windowSize == 0 ? 0:1);
        System.out.println("window: "+ index+";  " + item.getValue() + " ; t: " + t);
        Window w = windows.get(index-1);
        w.addItem(item);
        return true;
    }

    public static void main(String[] args) {
        long t = System.currentTimeMillis();

        System.out.println(t);

//        int ts = (int) (t % 60000);

        int ts = 55000;

        System.out.println(ts);

        System.out.println(ts / 5000 + (ts!=0 && ts % 5000 == 0 ? 0:1));



    }

    public long getInterval() {
        return interval;
    }

    public void setInterval(int interval) {
        this.interval = interval;
    }

    public int getWindowSize() {
        return windowSize;
    }

    public void setWindowSize(int windowSize) {
        this.windowSize = windowSize;
    }

    public List<Window> getWindows() {
        return windows;
    }

    public void setWindows(List<Window> windows) {
        this.windows = windows;
    }
}
